import type { TreeNode } from '@/types'
import { getUser } from '@/utils/auth'
/**
 * 将扁平数组转换为树形结构
 * @param flatArray 扁平数组，包含 id, name, parentId, devCount 字段
 * @param rootParentId 根节点的 parentId 值，默认为 0
 * @param hideEmptyDirectories 是否隐藏空目录（devCount=0），默认为 false
 * @returns 树形结构数组
 */
export function buildTree(
  flatArray: Array<{ id: number; name: string; parentId: number; devCount?: number }>, 
  rootParentId: number = 0,
  hideEmptyDirectories: boolean = false
): TreeNode[] {
  // 验证输入参数
  if (!Array.isArray(flatArray)) {
    console.error('buildTree: flatArray must be an array, got:', typeof flatArray, flatArray)
    throw new Error('buildTree: 输入参数必须是数组')
  }
  
  if (flatArray.length === 0) {
    console.log('buildTree: empty array provided, returning empty tree')
    return []
  }
  
  // 如果需要隐藏空目录，先过滤掉 devCount=0 的节点
  let filteredArray = flatArray
  if (hideEmptyDirectories && getUser().id!==1) {
    filteredArray = flatArray.filter(item => {
      const devCount = item.devCount ?? 0
      return devCount > 0
    })
    console.log(`buildTree: filtered ${flatArray.length - filteredArray.length} empty directories`)
  }
  
  // 创建节点映射表
  const nodeMap = new Map<number, TreeNode>()
  
  // 初始化所有节点
  filteredArray.forEach((item, index) => {
    // 验证每个元素的结构
    if (!item || typeof item !== 'object') {
      console.error(`buildTree: invalid item at index ${index}:`, item)
      throw new Error(`buildTree: 数组元素 ${index} 不是有效对象`)
    }
    
    if (typeof item.id === 'undefined' || typeof item.name !== 'string' || typeof item.parentId === 'undefined') {
      console.error(`buildTree: invalid item structure at index ${index}:`, item)
      throw new Error(`buildTree: 数组元素 ${index} 缺少必要字段 (id, name, parentId)`)
    }
    
    nodeMap.set(item.id, {
      id: item.id,
      name: item.name,
      parentId: item.parentId,
      children: [],
      devices: [],
      devCount: item.devCount ?? 0
    })
  })
  
  // 构建树形结构
  const rootNodes: TreeNode[] = []
  
  filteredArray.forEach(item => {
    const node = nodeMap.get(item.id)!
    
    if (item.parentId === rootParentId) {
      // 根节点
      rootNodes.push(node)
    } else {
      // 子节点，添加到父节点的 children 中
      const parent = nodeMap.get(item.parentId)
      if (parent) {
        if (!parent.children) {
          parent.children = []
        }
        parent.children.push(node)
      }
    }
  })
  
  return rootNodes
}

/**
 * 根据ID查找树形节点
 * @param tree 树形结构数组
 * @param id 要查找的节点ID
 * @returns 找到的节点或null
 */
export function findNodeById(tree: TreeNode[], id: number): TreeNode | null {
  for (const node of tree) {
    if (node.id === id) {
      return node
    }
    
    if (node.children) {
      const found = findNodeById(node.children, id)
      if (found) {
        return found
      }
    }
  }
  
  return null
}

/**
 * 获取树形结构的所有节点ID
 * @param tree 树形结构数组
 * @returns 所有节点ID的数组
 */
export function getAllNodeIds(tree: TreeNode[]): number[] {
  const ids: number[] = []
  
  function traverse(nodes: TreeNode[]) {
    nodes.forEach(node => {
      ids.push(node.id)
      if (node.children) {
        traverse(node.children)
      }
    })
  }
  
  traverse(tree)
  return ids
}

/**
 * 获取指定节点的所有子节点ID（包括自身）
 * @param tree 树形结构数组
 * @param nodeId 节点ID
 * @returns 子节点ID数组
 */
export function getChildNodeIds(tree: TreeNode[], nodeId: number): number[] {
  const node = findNodeById(tree, nodeId)
  if (!node) {
    return []
  }
  
  const ids: number[] = [nodeId]
  
  function traverse(nodes: TreeNode[]) {
    nodes.forEach(child => {
      ids.push(child.id)
      if (child.children) {
        traverse(child.children)
      }
    })
  }
  
  if (node.children) {
    traverse(node.children)
  }
  
  return ids
}
